<template>
  <div class="profile-container">
    <!-- 添加一个顶部占位空间 -->
    <div class="nav-spacer"></div>
    
    <!-- 顶部个人信息卡片 -->
    <div class="profile-header">
      <div class="profile-cover"></div>
      <div class="profile-info">
        <div class="avatar-wrapper">
          <el-avatar 
            :size="120" 
            :src="authStore.userAvatar || defaultUserAvatar"
            @error="() => true"
          />
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            accept=".jpg,.jpeg,.png"
            :http-request="handleAvatarUpload"
          >
            <el-button class="avatar-edit" circle>
              <el-icon><Camera /></el-icon>
            </el-button>
          </el-upload>
        </div>
        <div class="user-info">
          <h2 class="username">{{ userInfo.username }}</h2>
          <p class="user-role">{{ userInfo.role }}</p>
          <div class="user-stats">
            <div class="stat-item">
              <span class="stat-value">{{ userInfo.followers }}</span>
              <span class="stat-label">关注者</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ userInfo.following }}</span>
              <span class="stat-label">关注中</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ userInfo.collections }}</span>
              <span class="stat-label">收藏</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="profile-content">
      <el-tabs v-model="activeTab" class="profile-tabs">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form 
            :model="form" 
            :rules="rules" 
            ref="formRef" 
            label-position="top"
            class="profile-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="form.nickname" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="个人简介" prop="bio">
              <el-input 
                v-model="form.bio" 
                type="textarea" 
                :rows="4"
                placeholder="介绍一下自己吧..."
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="updateProfile" :loading="loading">
                保存修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <div class="security-settings">
            <div class="setting-item">
              <div class="setting-info">
                <h4>修改密码</h4>
                <p>定期修改密码可以保护账号安全</p>
              </div>
              <el-button @click="showChangePassword">修改</el-button>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <h4>绑定手机</h4>
                <p>已绑定：{{ maskPhone(form.phone) }}</p>
              </div>
              <el-button @click="showChangePhone">修改</el-button>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <h4>绑定邮箱</h4>
                <p>已绑定：{{ maskEmail(form.email) }}</p>
              </div>
              <el-button @click="showChangeEmail">修改</el-button>
            </div>
          </div>
        </el-tab-pane>

        <!-- 我的收藏 -->
        <el-tab-pane label="我的收藏" name="favorites">
          <div class="favorites-section">
            <FavoritesList />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input 
            v-model="passwordForm.currentPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Camera } from '@element-plus/icons-vue';
import { useAuthStore } from '@/stores/authStore';
import { useFavoritesStore } from '@/stores/favoritesStore';
import FavoritesList from '@/components/FavoritesList.vue';
import defaultUserAvatar from '@/assets/images/default_user_avatar.jpg';

// 状态管理
const activeTab = ref('basic');
const loading = ref(false);
const passwordLoading = ref(false);
const passwordDialogVisible = ref(false);
const formRef = ref();
const passwordFormRef = ref();

const authStore = useAuthStore();
const favoritesStore = useFavoritesStore();

// 用户信息 (部分信息从 authStore 获取)
const userInfo = reactive({
  username: authStore.currentUser?.username || '张三',
  role: authStore.currentUser?.role || '非遗爱好者',
  followers: 128,
  following: 56,
  collections: 32
});

// 表单数据 (初始化时从 store 或 userInfo 获取)
const form = ref({
  username: authStore.currentUser?.username || '张三',
  nickname: authStore.currentUser?.nickname || '非遗达人',
  email: authStore.currentUser?.email || 'zhangsan@example.com',
  phone: authStore.currentUser?.phone || '13800138000',
  bio: authStore.currentUser?.bio || '热爱传统文化，致力于非遗传承与保护。'
});

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '不能超过200个字符', trigger: 'blur' }
  ]
};

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 收藏数据
const collections = ref([
  {
    id: 1,
    title: '剪纸艺术展',
    description: '传统剪纸艺术与现代设计的完美结合',
    image: 'https://img.zcool.cn/community/01b2e95e6e2e2fa8012193a3e2e1e7.jpg',
    category: '传统美术',
    date: '2024-01-15'
  },
  {
    id: 2,
    title: '陶瓷工艺展',
    description: '景德镇传统陶瓷工艺展示',
    image: 'https://img.zcool.cn/community/01b2e95e6e2e2fa8012193a3e2e1e7.jpg',
    category: '传统技艺',
    date: '2024-01-10'
  }
]);

// 方法
const updateProfile = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    // 处理更新逻辑
    await new Promise(resolve => setTimeout(resolve, 1000));
    ElMessage.success('信息更新成功！');
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const handleAvatarUpload = async (options) => {
  try {
    const file = options.file;
    // 先进行文件验证
    const isValid = await beforeAvatarUpload(file);
    if (!isValid) {
      return;
    }

    // 使用 authStore 的 updateAvatar 方法更新头像
    const result = await authStore.updateAvatar(file);
    if (result) {
      ElMessage.success('头像更新成功！');
    }
  } catch (error) {
    console.error('Avatar upload error:', error);
    ElMessage.error(error.message || '头像更新失败！');
  }
};

const beforeAvatarUpload = (file) => {
  return new Promise((resolve) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG && !isPNG) {
      ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
      resolve(false);
      return;
    }
    if (!isLt2M) {
      ElMessage.error('上传头像图片大小不能超过 2MB!');
      resolve(false);
      return;
    }
    resolve(true);
  });
};

const showChangePassword = () => {
  passwordDialogVisible.value = true;
};

const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate();
    passwordLoading.value = true;
    // 处理密码修改逻辑
    await new Promise(resolve => setTimeout(resolve, 1000));
    ElMessage.success('密码修改成功！');
    passwordDialogVisible.value = false;
  } catch (err) {
    console.error(err);
  } finally {
    passwordLoading.value = false;
  }
};

const showChangePhone = () => {
  // 实现手机号修改逻辑
};

const showChangeEmail = () => {
  // 实现邮箱修改逻辑
};

// 工具方法
const maskPhone = (phone) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

const maskEmail = (email) => {
  const [name, domain] = email.split('@');
  return `${name.charAt(0)}***@${domain}`;
};
</script>

<style scoped>
/* 添加导航栏占位空间 */
.nav-spacer {
  height: 65px; /* 进一步减少占位空间高度 */
  width: 100%;
}

.profile-container {
  @apply min-h-screen bg-gray-50;
  margin-top: 50px; /* 减少顶部外边距 */
}

/* 顶部个人信息卡片 */
.profile-header {
  @apply relative bg-white shadow-sm;
  margin-top: 0; /* 移除顶部外边距 */
}

.profile-cover {
  @apply h-44 bg-gradient-to-r from-primary-500 to-primary-600; /* 稍微降低封面高度 */
}

.profile-info {
  @apply max-w-7xl mx-auto px-6 pb-4; /* 减少底部内边距 */
  transform: translateY(-60px);
}

/* 确保头像容器有足够的空间 */
.avatar-wrapper {
  position: relative;
  display: inline-block;
}

/* 调整头像编辑按钮的位置 */
.avatar-edit {
  position: absolute;
  right: 0;
  bottom: 0;
  padding: 6px;
  transform: translate(25%, 25%);
}

/* 优化头像编辑按钮样式 */
.avatar-uploader {
  display: inline-block;
}

/* 确保上传按钮不会被其他元素遮挡 */
.el-upload {
  position: relative;
  z-index: 10;
}

/* 调整用户信息区域的间距 */
.user-info {
  @apply mt-5; /* 进一步减少头像和用户信息之间的间距 */
}

.username {
  @apply text-2xl font-bold text-gray-800;
}

.user-role {
  @apply text-gray-600 mt-1;
}

.user-stats {
  @apply flex gap-8 mt-4;
}

.stat-item {
  @apply flex flex-col items-center;
}

.stat-value {
  @apply text-xl font-semibold text-gray-800;
}

.stat-label {
  @apply text-sm text-gray-500;
}

/* 主要内容区域 */
.profile-content {
  @apply max-w-7xl mx-auto px-6 py-4 -mt-2; /* 进一步减少内容区域的间距 */
}

.profile-tabs {
  @apply bg-white rounded-lg shadow-sm p-6;
}

.profile-form {
  @apply max-w-3xl;
}

/* 安全设置 */
.security-settings {
  @apply space-y-6;
}

.setting-item {
  @apply flex justify-between items-center p-4 border-b border-gray-100 last:border-0;
}

.setting-info h4 {
  @apply text-lg font-medium text-gray-800 mb-1;
}

.setting-info p {
  @apply text-gray-500;
}

/* 收藏列表 */
.collections-grid {
  @apply grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6;
}

.collection-card {
  @apply overflow-hidden;
}

.collection-image {
  @apply w-full h-48 object-cover;
}

.collection-info {
  @apply p-4;
}

.collection-info h4 {
  @apply text-lg font-medium text-gray-800 mb-2;
}

.collection-info p {
  @apply text-gray-600 text-sm mb-4 line-clamp-2;
}

.collection-meta {
  @apply flex justify-between items-center;
}

.collection-date {
  @apply text-sm text-gray-500;
}

/* Element Plus 样式覆盖 */
:deep(.el-tabs__nav-wrap::after) {
  @apply h-0.5;
}

:deep(.el-tabs__item) {
  @apply text-lg;
}

:deep(.el-tabs__item.is-active) {
  @apply text-primary-500;
}

:deep(.el-form-item__label) {
  @apply font-medium;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .profile-info {
    @apply text-center;
  }

  .user-stats {
    @apply justify-center;
  }

  .security-settings {
    @apply px-4;
  }
}
</style> 